<template>
  <div id="read"></div>
</template>

<script lang="ts" setup>
import Epub from 'epubjs'
import type { Book, Rendition } from 'epubjs'

const emits = defineEmits(['toogleNav'])

const initEpub = (url: string) => {
  const book: Book = new (Epub as any)(url)
  const rendition = book.renderTo('read', {
    width: innerWidth,
    height: innerHeight,
  })
  rendition.display()
  let touchstartX = 0
  let touchStartTime = 0

  const prevPage = () => {
    rendition && rendition.prev()
  }
  const nextPage = () => {
    rendition && rendition.next()
  }
  const toogleTitleAndMenu = () => {
    console.log('toogleNav')
    emits('toogleNav')
  }

  rendition.on('touchstart', (event: any) => {
    touchstartX = event.changedTouches[0].clientX
    touchStartTime = event.timeStamp
  })

  rendition.on('touchend', (event: any) => {
    const offsetX = event.changedTouches[0].clientX - touchstartX
    const time = event.timeStamp - touchStartTime
    console.log(offsetX, time)
    if (time < 500 && offsetX > 150) {
      prevPage()
    } else if (time < 500 && offsetX < -150) {
      nextPage()
    } else {
      toogleTitleAndMenu()
    }
    event.stopPropagation()
  })
}
initEpub('http://127.0.0.1:8080/2.epub')
</script>
<style scoped></style>
